import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { LoggerService } from './logger.service';

/**
 * HTTP请求日志中间件
 * 记录所有HTTP请求的详细信息和响应时间
 */
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  constructor(private readonly logger: LoggerService) {
    this.logger.setContext('HTTP');
  }

  /**
   * 中间件处理函数
   * @param req 请求对象
   * @param res 响应对象
   * @param next 下一个中间件函数
   */
  use(req: Request, res: Response, next: NextFunction) {
    const { method, originalUrl, ip, headers } = req;
    const userAgent = headers['user-agent'] || '';
    const startTime = Date.now();

    // 记录请求信息
    this.logger.http({
      type: 'request',
      method,
      url: originalUrl,
      ip,
      userAgent,
    });

    // 捕获响应完成事件
    res.on('finish', () => {
      const { statusCode } = res;
      const contentLength = res.get('content-length') || 0;
      const responseTime = Date.now() - startTime;

      // 记录响应信息
      this.logger.http({
        type: 'response',
        method,
        url: originalUrl,
        statusCode,
        contentLength,
        responseTime: `${responseTime}ms`,
      });

      // 对于错误响应，记录更详细的信息
      if (statusCode >= 400) {
        const logLevel = statusCode >= 500 ? 'error' : 'warn';
        this.logger[logLevel]({
          type: 'response_error',
          method,
          url: originalUrl,
          statusCode,
          responseTime: `${responseTime}ms`,
          headers: req.headers,
          query: req.query,
          body: req.body,
        });
      }
    });

    next();
  }
}
